<template>
  <div>
    <!-- B端订单查看-->
    <TopFilter ref="topfrom" :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110" @resetChange="resetChange" :isSubmitBtn="isShowBtn"></TopFilter>
    <Spin :spinning="exportLoading" tip="Loading...">
      <el-tabs v-model="activeName" @tab-click="tabsHandleClick" :before-leave="beforeHandle">
        <el-tab-pane label="采购订单" name="first">
          <FilterTable
            ref="table"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            :datakey="'records'"
            columnsRef="OrderSideBQuery"
            :isSelectColumn="true"
            :onRowSelectChange="selectChangeHandle"
            :onColumnsChange="(columns) => (this.columns = columns)"
          >
            <template slot="controls">
              <multiuse-button size="small" type="primary" @click="addHandle(1)">导 出</multiuse-button>
            </template>
          </FilterTable>
        </el-tab-pane>

        <el-tab-pane label="订单车辆" name="second">
          <FilterTable
            ref="tableInfo"
            height="auto"
            :columns="columns1"
            columnsRef="deliveryOrderQuery"
            :datakey="'records'"
            :fetchapi="fetchApi1"
            :params="fetchParams1"
            :isSelectColumn="true"
            :dataSource="tableList1"
            :onRowSelectChange="selectChangeHandle1"
            :onColumnsChange="(columns1) => (this.columns1 = columns1)"
          >
            <template slot="controls">
              <multiuse-button size="small" type="primary" @click="addHandle(2)" :disabled="ischange">保 存</multiuse-button>
            </template>
          </FilterTable>
        </el-tab-pane>
      </el-tabs>
    </Spin>

    <Drawer :visible.sync="detailVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <detailModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
  </div>
</template>
<script>
import { getList, getdeliveryList, saveList, cancelOrderById, exportList, exporturl } from '@/api/dealerSale/OrderManagement/OrderSideBQuery';
import detailModel from './detailModel';
import { exportExcelFile } from '@/utils';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
export default {
  name: 'OrderSideBQuery',
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      columns1: this.createdTable1(),
      fetchParams: {
        isDealer: 10041001,
        queryType: 'orderQuery'
      },
      fetchApi: getList,
      formData: {},
      fetchApi1: getdeliveryList,
      fetchParams1: {},
      ischange: true,
      exportLoading: false,
      detailVisible: false,
      tableList1: [],
      ProjectId: '',
      activeName: 'first',
      selectList: [],
      selectList1: [],
      isShowBtn: true
    };
  },
  components: {
    detailModel
  },
  mixins: [dictionary],
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.table = this.$refs.tableInfo.$refs.pageTable;
  },
  created() {
    //查询状态过滤
    this.getQueryStatus();
  },
  methods: {
    beforeHandle() {
      console.log(this.selectList,'列表');
      if (this.selectList.length === 0) {
        this.activeName = 'first';
        this.$notify({
          title: '警告',
          message: '至少选择一条数据',
          type: 'warning',
        });
        return false;
      }
    },
     //查询状态过滤
    getQueryStatus() {
      let statusList = this.createDictList('2417');
      console.log('所有状态',statusList);
      let index = statusList.findIndex(item =>{
　　　　　if(item.value == 24171001){
　　　　　　　return true
　　　　　}
　　　})
      statusList.splice(index, 1);
      this.topFilterList.find(item => item.fieldName == 'orderStatus').itemList = statusList;
    },
    async tabsHandleClick(tab, event) {
      console.log(tab);
      if (tab.index === '1') {
        this.isShowBtn = false;
        let orderIds = [];
        this.selectList.forEach((x) => {
          orderIds.push(x.orderId);
        });
        this.fetchParams1.orderIds = orderIds;
        this.fetchParams1 = Object.assign({}, this.fetchParams1);
      }
      if (tab.index === '0') {
        this.tableList1 = [];
        this.isShowBtn = true;
      }
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          placeholder: '请输入',
          dateType: 'month'
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'startDate|endDate',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange',
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2417'),
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: this.createDictList('2105'),
        },
        {
          type: 'SELECT',
          label: '紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
        },
      ];
    },

    selectChangeHandle(row) {
      this.selectList = row;
    },
    selectChangeHandle1(row) {
      this.selectList1 = row;
      if (this.selectList1.length > 0) {
        this.ischange = false;
      } else {
        this.ischange = true;
      }
    },
    async addHandle(type) {
      if (type == 1) {
        // let json = Object.assign({}, { CODE: 'CODE_0000011' }, this.fetchParams);
        // let res = await exporturl(json);

        // if (res.resultCode == 200) {
        //   this.$router.push('/admin/auth/oem/downloadCenter');
        // }
        
        this.$refs.topfrom.SUBMIT_FORM();

        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            let json = this.fetchParams;
            this.exportLoading = true;

            exportList(json)
              .then(response => {
                exportExcelFile(response.data, 'B端订单查看');
                this.exportLoading = false;
              })
              .catch(err => {
                console.log(err);
              });
          })
          .catch(() => {
            console.log('456');
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });

      } else if (type == 2) {
       if (!this.ischange) {
          await this.$confirm('是否保存选定的数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            this.ischange = true;
            this.selectList1.map((x)=>{
              x.address = x.addressDTOS.find(y => y.addressId == x.addressId).address 
            });
            let res = await saveList(this.selectList1);
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
              });
               this.ischange = false;
              this.isOpen = true;
              this.activeName = 'first';
              this.table.EXECUTE_DELETE(this.selectList1);
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
       }
      }
    },
    changeHandle(params) {
      this.fetchParams.projectCode = this.ProjectId;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async editHandle(data, type) {
      if (type === 1) {
        this.formData = data;
        this.detailVisible = true;
      }else {
        await this.$confirm('是否确定取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await cancelOrderById({deliveryOderIdes: [data.id]});
            if (res.resultCode == 200) {
              let orderIdList = [];
              for (let i = 0; i < this.selectList.length; i++) {
                orderIdList[i] = this.selectList[i].orderId;
              }
              console.log('主单ids:',orderIdList);
              this.tableList1 = [];
              const res = await getdeliveryList({orderIds: orderIdList});
              this.table.EXECUTE_INSERT(res.data.records);
              this.$notify({
                title: '成功',
                message: '取消成功',
                type: 'success',
              });
            }
          })
          .catch(() => {});
      }
    },
    emitcloseHandler() {
      this.detailVisible = false;
    },
    resetChange(val) {
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    changeDealerAddress(value,row) {
      for (let address of row.addressDTOS) {
        if(address.addressId == value) {
          row.deliveryCityName = address.cityName;
          row.linkMan = address.linkMan;
          row.linkPhone = address.linkPhone;
          return;
        }
      }
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2105'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2105')}</span>;
          },
        },
        {
          title: '紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2101'),
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2417'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderStatus, '2417')}</span>;
          },
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearAndMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2409'),
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '提报数量',
          dataIndex: 'orderTotalNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'input',
           render: (p) => {
            return <span>{p.row.createdName}</span>;
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
    createdTable1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)}>
                  详情
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)} disabled={props.row.orderStatus != 24151001}>
                  取消
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '是否最优先结算',
          dataIndex: 'firstPrioritySettle',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'checkbox',
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 },
          ],
          onChange: (index, data) => {
            if (data.firstPrioritySettle === 10041001) {
              data.prioritySettle = 10041002;
            }
          },
        },
        {
          title: '是否优先结算',
          dataIndex: 'prioritySettle',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'checkbox',
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 },
          ],
          onChange: (index, data) => {
            if (data.prioritySettle === 10041001) {
              data.firstPrioritySettle = 10041002;
            }
          },
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单管理号',
          dataIndex: 'doNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2105'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2105')}</span>;
          },
        },
        {
          title: '紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        {
          title: '订单来源',
          dataIndex: 'isApp',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单明细状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return <span>{this.createDictText(p.row.orderStatus, '2415')}</span>;
          }
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.vehicleUse, '2416')}</span>;
          },
        },

        {
          title: '资金类型',
          dataIndex: 'accountId',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.accountId}
                required
                placeholder="请选择"
                onChange={(value) => {
                  p.row.accountId = value;
                }}
              >
                {p.row.accountTypes.map((item) => (
                  <el-option key={item.accountId} label={item.accountTypeName} value={item.accountId} />
                ))}{' '}
              </el-select>
            );
          },
        },
        {
          title: '结算价格',
          dataIndex: 'sapSettlementPrice',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 100,
          precision: 2,
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '基础折扣',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
       {
          title: '终端奖',
          dataIndex: 'sapTerminalBonus',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '优质服务奖',
          dataIndex: 'sapServiceBonus',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '促销1',
          dataIndex: 'sapPromotionPriceA',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '促销2',
          dataIndex: 'sapPromotionPriceB',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: (p) => {
            return <span>{this.createDictText(p.row.isRebate, '1004')}</span>;
          },
        },
        {
          title: '返利使用金额',
          dataIndex: 'rebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '收车地址',
          dataIndex: 'addressId',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.addressId}
                required
                placeholder="请选择"
                 onChange={(value) => {
                  p.row.addressId = value;
                  this.changeDealerAddress(value,p.row);
                }}
              >
                {p.row.addressDTOS.map((item) => (
                  <el-option key={item.addressId} label={item.address} value={item.addressId} />
                ))}
              </el-select>
            );
          },
        },
        {
          title: '送达城市',
          dataIndex: 'deliveryCityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系电话',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
